/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.business.fee.core.service.processor.account;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.RandomUtil;
import info.peigen.hotpot.business.account.facade.order.trans.TransferOrder;
import info.peigen.hotpot.business.account.facade.result.trans.TransferResult;
import info.peigen.hotpot.business.fee.core.domain.Fee;
import info.peigen.hotpot.business.fee.core.service.processor.base.AbstractFeeServiceProcessor;
import info.peigen.hotpot.common.core.result.ResultCode;
import info.peigen.hotpot.common.service.base.exception.BusinessException;
import info.peigen.hotpot.common.service.base.processor.Processor;
import info.peigen.hotpot.common.service.base.processor.ProcessorServiceContext;
import org.noear.solon.annotation.Component;

import static info.peigen.hotpot.business.account.facade.enums.AccountAction.Transfer;

/**
 * <b>(CalculateFeeProcessor)</b>
 *
 * @author LiHai
 * @version 1.0.0
 * @since 2022/9/6
 */
@Component
public class FeeAccountTransferProcessor extends AbstractFeeServiceProcessor implements Processor {
    @Override
    public Integer level() {
        return 90;
    }

    @Override
    public void execute(ProcessorServiceContext serviceContext) {
        Fee domain = (Fee) serviceContext.getDomain();
        Assert.notNull(domain, () -> new BusinessException(ResultCode.FAILURE, "收费失败![fee=" + domain + "]"));
        if (!transfer(domain)) {
            throw new BusinessException(ResultCode.FAILURE, "收费失败,账务收费失败![fee=" + domain + "]");
        }
    }

    private Boolean transfer(Fee domain) {
        TransferOrder order = genTransferOrder().setPayerAccountId(domain.getChargeAccount().getAccountId())
                .setPayeeAccountId(domain.getFeeAccount().getAccountId());
        order.setTransAmount(domain.getFeeAmount()).setTradeId(domain.getTradeId());
        TransferResult result = accountTransService.transfer(order);
        return result.success();
    }

    private TransferOrder genTransferOrder() {
        return TransferOrder.builder().bizOrderNo(RandomUtil.randomString(20)).productCode(Transfer.code()).build();
    }
}